package com.yds.bluetooth

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.TextUtils
import android.util.Log
import java.lang.Exception

/**
 * 全量蓝牙扫描
 */
@SuppressLint("StaticFieldLeak")
@Suppress("Unused")
 object ScanAllDeviceManager {
    private const val TAG = "YDS蓝牙"

    private var mContext: Context? = null
    private var mBluetoothAdapter: BluetoothAdapter? = null

    // 蓝牙名称是否可以为空
    var nameCanEmpty: Boolean = false

    // 连接蓝牙设备结果回调
    var scanResultCallback: ((BluetoothDevice) -> Unit)? = null

    // 扫描到的蓝牙设备
    private val mListBluetoothDevices = mutableListOf<BluetoothDevice>()

    /**
     * 开始扫描
     */
    fun startAllScanDevice(context: Context, bluetoothAdapter: BluetoothAdapter?, nameCanEmpty: Boolean = false, scanResultCallback: (BluetoothDevice) -> Unit) {
        mContext = context
        mBluetoothAdapter = bluetoothAdapter
        this.nameCanEmpty = nameCanEmpty
        this.scanResultCallback = scanResultCallback
        mListBluetoothDevices.clear()

        // 注册广播接收器
        context.registerReceiver(receiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        bluetoothAdapter?.startDiscovery()
    }

    /**
     * 终止扫描
     */
    fun stopAllScanDevice() {
        mBluetoothAdapter?.cancelDiscovery()
        // 取消注册广播接收器
        try {
            mContext?.unregisterReceiver(receiver)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private val receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_FOUND == action) {
                val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                device?.let {
                    if (!nameCanEmpty) {
                        if (!TextUtils.isEmpty(it.name)) {
                            addDiscoverDevice(it)
                        } else {
                            Log.i("发现无名称设备", "发现无名称设备: ${it.name} ${it.address}")
                        }
                    } else {
                        addDiscoverDevice(it)
                    }
                }
            }
        }
    }

    /**
     * 添加发现的蓝牙设备
     */
    private fun addDiscoverDevice(device: BluetoothDevice) {
        if (mListBluetoothDevices.isEmpty()) {
            Log.i(TAG, "发现全量设备: ${device.name} ${device.address} ${device.type}")
            scanResultCallback?.invoke(device)
            mListBluetoothDevices.add(device)
        } else {
            var hasSameDevice = false
            mListBluetoothDevices.forEach { item ->
                if (item.address == device.address) {
                    hasSameDevice = true
                }
            }
            if (!hasSameDevice) {
                Log.i(TAG, "发现全量设备: ${device.name} ${device.address} ${device.type}")
                scanResultCallback?.invoke(device)
                mListBluetoothDevices.add(device)
            }
        }
    }

    /**
     * 查询全部搜索到的蓝牙设备
     */
    fun queryAllScanBluetoothDevices(): List<BluetoothDevice> {
        return mListBluetoothDevices
    }
}